/**
 * 
 */

package com.pp.admin.common.client;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.pp.admin.common.client.helper.JavaScriptCommon;
import com.pp.admin.common.client.i18.I18;

/**
 * @author pandurang
 */
public class AdminLocale extends ListBox implements I18 {
	
	public static final String	SELECT					= "select";
	
	public static final String	LOCALE					= "locale";
	
	private static final String	URL_QUERY_STR_SPLITTER	= "?";
	
	private static final String	PARAM_SPLITTER			= "&";
	
	public HorizontalPanel		parent					= null;
	
	public AdminLocale( HorizontalPanel parent ) {

		setName( LOCALE );
		String selectedLocale = Location.getParameter( AdminLocale.LOCALE );
		if ( selectedLocale == null || "".equals( selectedLocale ) ) {
			selectedLocale = "en";
		}
		addItem( myConstants.marathi(), "mr" );
		addItem( myConstants.hindi(), "hi" );
		addItem( myConstants.english(), "en" );
		int localeCount = getItemCount();
		for ( int index = 0; index < localeCount; index++ ) {
			if ( getValue( index ).equalsIgnoreCase( selectedLocale ) ) {
				setSelectedIndex( index );
				break;
			}
		}
		
		addChangeHandler( new ChangeHandler() {
			
			@Override
			public void onChange( ChangeEvent event ) {

				String path = Location.getHref();
				String location = null;
				if ( path != null ) {
					if ( path.contains( LOCALE ) ) {
						location = path.substring( 0, ( path.indexOf( LOCALE ) - 1 ) );
					} else {
						location = path;
					}
					if ( location.contains( AdminLocale.URL_QUERY_STR_SPLITTER ) ) {
						location += AdminLocale.PARAM_SPLITTER;
					} else {
						location += AdminLocale.URL_QUERY_STR_SPLITTER;
					}
				}
				String selectLocale = getSelectedLocale();
				if ( !SELECT.equals( selectLocale ) ) {
					JavaScriptCommon.redirectToUrl( location + LOCALE + "=" + selectLocale );
				}
			}
		} );
	}
	
	public String getSelectedLocale() {

		return getValue( getSelectedIndex() );
	}
	
}
